import {Service} from "@/core/service";
import mongodb from "mongodb";
import {MONGODB_CONFIG} from "@/manage";

export    class MongoService extends Service{
    public db:mongodb.Db;
    public client:mongodb.MongoClient;
    private  dbName = MONGODB_CONFIG.MONGODB_NAME;
    private  url = `mongodb://${MONGODB_CONFIG.MONGODB_IP}:${MONGODB_CONFIG.MONGODB_HOST}`;

    protected mounted() {
        super.mounted();
        mongodb.MongoClient.connect(
                this.url,
                {auth: {user:MONGODB_CONFIG.MONGODB_NAME,password:MONGODB_CONFIG.MONGODB_PWD}},
                (err:mongodb.MongoError, client:mongodb.MongoClient
            ) => {
                if(err){
                    console.log("链接错误", err);
                }else{
                    this.client = client;
                    this.db = client.db(this.dbName);
                    console.log("连接上db", this.db)
                }
        })
    }

    public changeDb(dbName:string){
        if(this.client){
            this.db = this.client.db(dbName);
        }
    }

    public  createCollection(coll_name:string){
        if(this.db){
            this.db.createCollection(coll_name, (err:mongodb.MongoError , res:mongodb.Collection<any>) => {
                if(err){
                    console.log(err,"错误")
                }else {
                    console.log("数据集和创建成功!", res)
                }
            })
        }else {
            console.log("数据库不存在")
        }
    }

    public close(){
        if(this.client){
            this.client.close()
        }
    }
}
